/**
 * 
 */
package data;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONObject;
import org.json.JSONTokener;






/**
 * @author Mathias
 *
 */
public class ZugmonitorConnection {

	public static String HOST = "http://zugmonitor.sueddeutsche.de/api/";
	URL url;

	public static enum REQUEST { STATIONS, TRAINS };
	public REQUEST request;

	HttpURLConnection connection;
	public JSONObject input;

	public ZugmonitorConnection(REQUEST req){
		setRequest(req);
	}

	public void setRequest(REQUEST req){
		this.request = req;
		try {
			request();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			throw new IllegalArgumentException("invalid url");
		}
	}



	private void request() throws FileNotFoundException {
		if (this.request == null){
			throw new IllegalStateException("request not defined");
		}

		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String dateString = (dateFormat.format(date));


		try {
			switch (this.request){
			case STATIONS:	url = new URL(HOST+"stations");
							break;
			case TRAINS:	url = new URL(HOST+"trains/"+dateString);
							break;
			default:		throw new IllegalStateException("invalid request");

			}
			
			//System.out.println(url.getPath());
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			InputStream in = connection.getInputStream();

			JSONTokener tokener = new JSONTokener(in);
			input = new JSONObject(tokener);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}



	}

}
